// 管理用户数据相关

import { defineStore } from 'pinia'
import { ref } from 'vue'
import { UserLoginService } from '@/apis/user'
import { useCartStore } from './cartStore'
import { logoutService } from "@/apis/user";
import { getUserInfoService } from "@/apis/user";
import { useRouter } from 'vue-router';
const router = useRouter()

export const useUserStore = defineStore('user', () => {
  const cartStore = useCartStore()
  // 1. 定义管理用户数据的state
  const userInfo = ref({})
  // 2. 定义获取接口数据的action函数
  const getUserInfo = async ({ username, password }) => {
    // alert('++++++++++++++')
    const res = await UserLoginService({ username, password })
    userInfo.value = res.data
    console.log('userInfo.value',userInfo.value);
    localStorage.setItem('USER_KEY', userInfo.value.data)
      //ElMessage.success('成功登录',res)
      // router.push('/home')
      return res


      // ElMessage.error('用户名或密码错误')
      // console.log('1111111111用户名或密码错误');
      // alert("---------------")
    
    // alert("--------------")

    

    
    
    
  }

  // 退出时清除用户信息
  const clearUserInfo = async() => {
    const res=await logoutService()
    console.log("退出登录",res);
    userInfo.value = {}
    // 执行清除购物车的action
    cartStore.clearCart()
  }

  // const imgUrl=ref()

  const Info=ref({})
  const getUserInfoData=async()=>{
    const res=await getUserInfoService()
    // console.log(res);
    Info.value=res.data.data

    console.log("------------------------",Info.value);
  }
  getUserInfoData()
  const changeInfo=(data)=>{
    Info.value=data
    getUserInfoData()
  }
  // const getUserInfoData=async()=>{
  //     const res=await getUserInfoService()
  //     console.log(res);
  //     Info.value=res.data.data
  // }
  // getUserInfoData()
  // 3. 以对象的格式把state和action return

  // const setUserInfo=()=>{
  //   localStorage.setItem('USER_KEY', userInfo.value.data)
  // }
  return {
    userInfo,
    getUserInfo,
    clearUserInfo,
    Info,
    changeInfo,
    getUserInfoData,
  }
}, {
  persist: true,
})